/* Copyright (C) 2011 Riccardo Marson

   This file is part of OpenPool, an open-source game of pool. 

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   RICCARDO MARSON BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
   AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  See Readme.rtf for further information.
  
*/

#include "soundsystem.h"
#include "rescache.h"

#include <assert.h>


CSoundSystem::CSoundSystemListener::CSoundSystemListener(string name, CSoundSystem *parent) :
    CBaseEventListener(name)
{
    mParent = parent;
}

CSoundSystem::CSoundSystemListener::~CSoundSystemListener()
{

}

bool CSoundSystem::CSoundSystemListener::processEvent(EventPtr event)
{
    eEventType evT = event->getEventType();

    switch (evT)
    {
    case EV_CAMERA_MOVED: {
        CCameraMovedEvent *m_event = dynamic_cast<CCameraMovedEvent*>(event.get());
        mParent->mCurrentCameraPosition = m_event->position();
        mParent->updateUserPosition();
        break;
    }
    case EV_BALL_COLLISION: {
        CBallCollisionEvent *bc_event = dynamic_cast<CBallCollisionEvent*>(event.get());
        mParent->playBallHitsBall(bc_event->collisionPoint());
        break;
    }
    case EV_TABLE_COLLISION: {
        CTableCollisionEvent *tc_event = dynamic_cast<CTableCollisionEvent*>(event.get());
        mParent->playBallHitsTable(tc_event->collisionPoint());
        break;
    }
    case EV_BALL_POCKETED: {
        CBallPocketedEvent *bp_event = dynamic_cast<CBallPocketedEvent*>(event.get());
        mParent->playBallInPocket(bp_event->position());
        break;
    }
    case EV_CUEBALL_POCKETED: {
        CCueBallPocketedEvent *bp_event = dynamic_cast<CCueBallPocketedEvent*>(event.get());
        mParent->playBallInPocket(bp_event->position());
        break;
    }
    case EV_CUEBALL_LAUNCHED: {
        CCueBallLaunchedEvent *cl_event = dynamic_cast<CCueBallLaunchedEvent*>(event.get());
        mParent->playCueHitsBall(cl_event->position());
        break;
    }
    //all other events are not handled. the default case should never be called, as each
    //listener is already registered only to events of interest. However, it is useful as
    //a precaution and to avoid compile-time warnings.
    default:
        return false;
    }

    return true;
}

CSoundSystem::CSoundSystem(string listenerName) :
    mEventListener( new CSoundSystemListener(listenerName, this) )
{
    CLogManager::getSingleton()->logMessage("Initialising Sound System...");

    mBallHitsBall = NULL;
    mBallHitsTable = NULL;
    mCueHitsBall = NULL;
    mBallFallsInPocket = NULL;
    mBkgMusic = NULL;
    mBtnClick = NULL;
    mTxtAccept = NULL;

    //register the listener in the Event Manager
    CEventManager::getSingleton()->registerListener(EV_CAMERA_MOVED, mEventListener);
    CEventManager::getSingleton()->registerListener(EV_BALL_COLLISION, mEventListener);
    CEventManager::getSingleton()->registerListener(EV_TABLE_COLLISION, mEventListener);
    CEventManager::getSingleton()->registerListener(EV_CUEBALL_LAUNCHED, mEventListener);
    CEventManager::getSingleton()->registerListener(EV_BALL_POCKETED, mEventListener);
    CEventManager::getSingleton()->registerListener(EV_CUEBALL_POCKETED, mEventListener);
}


CSoundSystem::~CSoundSystem()
{
    CLogManager::getSingleton()->logMessage("Sound System Shutting Down.");

    string name1 = "POL-white-stones-short.wav";
    string name2 = "cue_hits_ball.wav";
    string name3 = "ball_hits_ball.wav";
    string name4 = "ball_in_pocket.wav";
    string name5 = "ball_hits_bumper.wav";
    string name6 = "button_click.wav";
    string name7 = "text_accept.wav";

    CResourceCache::getSingletonPtr()->unloadResource(name1);
    CResourceCache::getSingletonPtr()->unloadResource(name2);
    CResourceCache::getSingletonPtr()->unloadResource(name3);
    CResourceCache::getSingletonPtr()->unloadResource(name4);
    CResourceCache::getSingletonPtr()->unloadResource(name5);
    CResourceCache::getSingletonPtr()->unloadResource(name6);
    CResourceCache::getSingletonPtr()->unloadResource(name7);

    CEventManager::getSingleton()->unregisterListener(mEventListener);

}

void CSoundSystem::updateUserPosition()
{
    //TODO: add camera heading to event info

    //Reset the listener (user) position
    sf::Listener::SetPosition(mCurrentCameraPosition.x(),
    		mCurrentCameraPosition.y(),
    		mCurrentCameraPosition.z() );

    sf::Listener::SetTarget(0.0, 3.24, 0.0);
}

void CSoundSystem::loadSoundResources()
{
    CLogManager::getSingleton()->logMessage("Loading Sound Resources...");

    // request sounds form the resource cache. they will be loaded if not already present.

    string name1 = "POL-white-stones-short.wav";
    string name2 = "cue_hits_ball.wav";
    string name3 = "ball_hits_ball.wav";
    string name4 = "ball_in_pocket.wav";
    string name5 = "ball_hits_bumper.wav";
    string name6 = "button_click.wav";
    string name7 = "text_accept.wav";

    // TODO: should substitute with a map of sound pointers, keyed with their names.

    ResHandlePtr res1 = CResourceCache::getSingletonPtr()->requestResource(name1, RES_SOUND);

    if (res1->getType() == RES_SOUND)
    {
    	CAudioResHandle* soundRes = dynamic_cast<CAudioResHandle*>(res1.get());
    	mBkgMusic = &(soundRes->sound);
    }

    ResHandlePtr res2 = CResourceCache::getSingletonPtr()->requestResource(name2, RES_SOUND);

    if (res1->getType() == RES_SOUND)
    {
    	CAudioResHandle* soundRes = dynamic_cast<CAudioResHandle*>(res2.get());
    	mCueHitsBall = &(soundRes->sound);
    }

    ResHandlePtr res3 = CResourceCache::getSingletonPtr()->requestResource(name3, RES_SOUND);

    if (res3->getType() == RES_SOUND)
    {
    	CAudioResHandle* soundRes = dynamic_cast<CAudioResHandle*>(res3.get());
    	mBallHitsBall = &(soundRes->sound);
    }

    ResHandlePtr res4 = CResourceCache::getSingletonPtr()->requestResource(name4, RES_SOUND);

    if (res4->getType() == RES_SOUND)
    {
    	CAudioResHandle* soundRes = dynamic_cast<CAudioResHandle*>(res4.get());
    	mBallFallsInPocket = &(soundRes->sound);
    }

    ResHandlePtr res5 = CResourceCache::getSingletonPtr()->requestResource(name5, RES_SOUND);

    if (res5->getType() == RES_SOUND)
    {
    	CAudioResHandle* soundRes = dynamic_cast<CAudioResHandle*>(res5.get());
    	mBallHitsTable = &(soundRes->sound);
    }

    ResHandlePtr res6 = CResourceCache::getSingletonPtr()->requestResource(name6, RES_SOUND);

    if (res6->getType() == RES_SOUND)
    {
    	CAudioResHandle* soundRes = dynamic_cast<CAudioResHandle*>(res6.get());
    	mBtnClick = &(soundRes->sound);
    }

    ResHandlePtr res7 = CResourceCache::getSingletonPtr()->requestResource(name7, RES_SOUND);

    if (res7->getType() == RES_SOUND)
    {
    	CAudioResHandle* soundRes = dynamic_cast<CAudioResHandle*>(res7.get());
    	mTxtAccept = &(soundRes->sound);
    }

    //Set the initial listener (user) position
    sf::Listener::SetPosition(mCurrentCameraPosition.x(),
    		mCurrentCameraPosition.y(),
    		mCurrentCameraPosition.z());

    sf::Listener::SetTarget(0.0, 3.24, 0.0);

    //the collision sound is a 3d sound and will react to changes in the position of the camera (user) and the
    //point where the collision happens.

    // set general sound attributes

    if (mCueHitsBall != NULL)
    {
    	mCueHitsBall->SetLoop(false);
    	mCueHitsBall->SetVolume(150.0);
    	mCueHitsBall->SetPitch(1.5);

    	// set attributes for 3d sounds
    	mCueHitsBall->SetRelativeToListener(false);
    	mCueHitsBall->SetMinDistance(20.0);
    	mCueHitsBall->SetAttenuation(5.0);
    }

    if (mBallHitsBall != NULL)
    {
    	mBallHitsBall->SetLoop(false);
    	mBallHitsBall->SetVolume(150.0);
    	mBallHitsBall->SetPitch(1.5);

        mBallHitsBall->SetRelativeToListener(false);
        mBallHitsBall->SetMinDistance(20.0);
        mBallHitsBall->SetAttenuation(5.0);
    }

    if (mBallFallsInPocket != NULL)
    {
    	mBallFallsInPocket->SetLoop(false);
    	mBallFallsInPocket->SetVolume(150.0);
    	mBallFallsInPocket->SetPitch(1.5);

        mBallFallsInPocket->SetRelativeToListener(false);
        mBallFallsInPocket->SetMinDistance(20.0);
        mBallFallsInPocket->SetAttenuation(5.0);
    }

    if (mBallHitsTable != NULL)
    {
    	mBallHitsTable->SetLoop(false);
    	mBallHitsTable->SetVolume(150.0);
    	mBallHitsTable->SetPitch(1.5);

        mBallHitsTable->SetRelativeToListener(false);
        mBallHitsTable->SetMinDistance(20.0);
        mBallHitsTable->SetAttenuation(5.0);
    }

    if (mBkgMusic != NULL)
    {
    	mBkgMusic->SetLoop(true);
    	mBkgMusic->SetVolume(60.0);
    	mBkgMusic->SetPitch(1.0);
    }

    if (mBtnClick != NULL)
    {
    	mBtnClick->SetLoop(false);
    	mBtnClick->SetVolume(100.0);
    	mBtnClick->SetPitch(1.0);
    }

    if (mTxtAccept != NULL)
    {
    	mTxtAccept->SetLoop(false);
    	mTxtAccept->SetVolume(100.0);
    	mTxtAccept->SetPitch(1.0);
    }

}

void CSoundSystem::startBackgroundMusic()
{
	if (mBkgMusic != NULL)
		mBkgMusic->Play();
}

void CSoundSystem::playBallHitsBall(CVector3 soundPosition)
{
    //the incoming sound position is in world coordinates, convert to GL / Screen coordinates

    CVector3 glSound;
    glSound.SetComponents( soundPosition.x(), soundPosition.z(), soundPosition.y() );

    if (mBallHitsBall != NULL)
    {
    	mBallHitsBall->SetPosition(glSound.x(), glSound.y(), glSound.z());

    	mBallHitsBall->Play();
    }
}

void CSoundSystem::playBallHitsTable(CVector3 soundPosition)
{
    //the incoming sound position is in world coordinates, convert to GL / Screen coordinates

    CVector3 glSound;
    glSound.SetComponents( soundPosition.x(), soundPosition.z(), soundPosition.y() );

    if (mBallHitsTable != NULL)
    {
    	mBallHitsTable->SetPosition(glSound.x(), glSound.y(), glSound.z());

    	mBallHitsTable->Play();
    }
}

void CSoundSystem::playBallInPocket(CVector3 soundPosition)
{
    //the incoming sound position is in world coordinates, convert to GL / Screen coordinates

    CVector3 glSound;
    glSound.SetComponents( soundPosition.x(), soundPosition.z(), soundPosition.y() );

    if (mBallFallsInPocket != NULL)
    {
    	mBallFallsInPocket->SetPosition(glSound.x(), glSound.y(), glSound.z());

    	mBallFallsInPocket->Play();
    }
}

void CSoundSystem::playCueHitsBall(CVector3 soundPosition)
{
    //the incoming sound position is in world coordinates, convert to GL / Screen coordinates

    CVector3 glSound;
    glSound.SetComponents( soundPosition.x(), soundPosition.z(), soundPosition.y() );

    if (mCueHitsBall != NULL)
    {
    	mCueHitsBall->SetPosition(glSound.x(), glSound.y(), glSound.z());

    	mCueHitsBall->Play();
    }
}

void CSoundSystem::backgroundMusicOn()
{
	if (mBkgMusic != NULL)
		mBkgMusic->Play();
}

void CSoundSystem::backgroundMusicOff()
{
	if (mBkgMusic != NULL)
		mBkgMusic->Pause();
}

bool CSoundSystem::musicIsPlaying()
{
	bool playing;

	if (mBkgMusic != NULL)
	{
		switch (mBkgMusic->GetStatus())
		{
		case sf::Sound::Playing:
			playing = true;
			break;
		case sf::Sound::Paused:
			playing = false;
			break;
		case sf::Sound::Stopped:
			playing = false;
			break;
		}
	}
	else
		playing = false;

    return playing;
}

void CSoundSystem::playButtonClick()
{
	if (mBtnClick != NULL)
		mBtnClick->Play();
}

void CSoundSystem::playTextAccepted()
{
	if (mTxtAccept != NULL)
		mTxtAccept->Play();
}
